package com.toKnow.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 加密用户信息：username, userpwd
 */
public class JwtUserSessionUtil {

    private static final long EXPIRE_TIME = 3 * 60 * 60 * 1000; // 过期时间3小时
    private static final String TOKEN_SECRET = "JwtUserSessionUtil"; // token私钥

    /**
     * 校验token是否正确
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     */
    public static String getInfo(String token, String fieldName) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(fieldName).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,15min后过期
     */
    public static String sign(String id, String username, String userpwd) {
        // 过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        // 私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        // 设置头部信息
        Map<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        // 附带username，userId信息，生成签名
        return JWT.create()
                .withHeader(header)
                .withClaim("id", id)
                .withClaim("username", username)
                .withClaim("userpwd", userpwd)
                .withExpiresAt(date)
                .sign(algorithm);
    }
}
